package com.shadow.study.test.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.util.Map;

public class JSONT {

    public static void main(String[] args) {
        // JSON 文件的路径（相对于 resources 文件夹）
        String filePath = "D:\\workspace\\projects-demo\\study\\study-9299-test\\src\\main\\resources\\json\\4.json";

        try {
            Reader reader = new FileReader(filePath);
            BufferedReader bufferedReader = new BufferedReader(reader);
            // 将文件内容逐行读取并拼接成一个字符串
            StringBuilder jsonString = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                jsonString.append(line);
            }
            bufferedReader.close();
            // 将字符串转换为 JSONObject 对象
            JSONObject jsonObject = JSONObject.parseObject(jsonString.toString());
            String message = getMessageByRuleTypeName((JSONObject) jsonObject.get("data"));
            System.out.println(message);
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getMessageByRuleTypeName(JSONObject data) {
        try {
            JSONArray dataData = data.getJSONArray("data");
            JSONObject dataObject = dataData.get(0) instanceof Map
                    ? new JSONObject((Map) dataData.get(0))
                    : (JSONObject) dataData.get(0);
            String name = dataObject.getString("ruleTypeName");
            if (StringUtils.equals("坐标检查", name)) {
                JSONArray messages = dataObject.getJSONArray("messages");
                JSONObject messageObject = messages.get(0) instanceof Map
                        ? new JSONObject((Map) messages.get(0))
                        : (JSONObject) messages.get(0);
                return messageObject.getString("message");
            } else {
                return "没找到";
            }
        } catch (Exception e) {
            System.out.println(1);
        }

        return "";
    }
}
